package com.example.publish_model;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.publish_model.entity.GifMsgEntity;
import com.example.publish_model.entity.MsgEntity;
import com.example.publish_model.entity.PopMsgEntity;
import com.example.publish_model.entity.TextMsgEntity;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class WebSocketService extends Service {
    private WebSocket webSocket;
    private long retryTime = 10 * 1000;//重连时间
    private MsgCallBack msgCallBack;

    public void setMsgCallBack(MsgCallBack msgCallBack) {
        this.msgCallBack = msgCallBack;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        connectWebSocket();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeWebSocket();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new WebSocketBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    private void connectWebSocket() {
        Request.Builder builder = new Request.Builder();
        builder.url(LiveConst.WEBSOCKETURL);
        Request request = builder.build();

        webSocket = new OkHttpClient.Builder().pingInterval(10, TimeUnit.SECONDS).build().newWebSocket(request, listener);

    }

    private WebSocketListener listener = new WebSocketListener() {
        @Override
        public void onOpen(@NonNull WebSocket webSocket, @NonNull Response response) {
            super.onOpen(webSocket, response);
            //开启
            try {
                Log.e("ZZQ", "onOpen: " + response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onClosed(@NonNull WebSocket webSocket, int code, @NonNull String reason) {
            super.onClosed(webSocket, code, reason);
            //关闭
        }

        @Override
        public void onFailure(@NonNull WebSocket webSocket, @NonNull Throwable t, @Nullable Response response) {
            super.onFailure(webSocket, t, response);
            //连接异常->重连
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //连接异常断开重新连接webSocket服务器
                    connectWebSocket();
                }
            }, 10 * 1000);
        }

        @Override
        public void onMessage(@NonNull WebSocket webSocket, @NonNull String text) {
            super.onMessage(webSocket, text);
            //接收服务器push来的消息
            if (text.equals("连接成功")) {
                Log.e("ZZQ", "onMessage: " + text);
                return;
            }
            int type = 0;
            try {
                JSONObject jsonObject = new JSONObject(text);
                type = jsonObject.getInt("type");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            MsgEntity entity = null;
            if (type==0){
                TextMsgEntity textMsgEntity = new Gson().fromJson(text, TextMsgEntity.class);
                entity = textMsgEntity;
            }else if (type == 1){
                PopMsgEntity popMsgEntity = new Gson().fromJson(text,PopMsgEntity.class);
                entity = popMsgEntity;
            }else if (type == 2){
                GifMsgEntity gifMsgEntity = new Gson().fromJson(text,GifMsgEntity.class);
                entity = gifMsgEntity;
            }
            Message msg = handler.obtainMessage();
            msg.what = 100;
            msg.obj = entity;
            handler.sendMessage(msg);
        }
    };


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            MsgEntity msgEntity = (MsgEntity) msg.obj;
            msgCallBack.msgCall(msgEntity);
        }
    };

    private void closeWebSocket() {
        if (webSocket != null) {
            webSocket.close(1000, "close");
        }
    }

    public class WebSocketBinder extends Binder {
        public WebSocketService getWebSocketService() {
            return WebSocketService.this;
        }
    }
}
